package com.hw01.service.impl;

import java.time.LocalDateTime;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.hw01.common.Result;
import com.hw01.common.ResultPage;
import com.hw01.common.UserInfo;
import com.hw01.constant.DelState;
import com.hw01.dto.OrganizationAddDto;
import com.hw01.dto.OrganizationQueryDto;
import com.hw01.dto.OrganizationUpdateDto;
import com.hw01.entity.Organization;
import com.hw01.mapper.OrganizationMapper;
import com.hw01.service.OrganizationService;
import com.hw01.vo.OrganizationVo;

/**
 * <p>
 * 部门 服务实现类
 * </p>
 *
 * @author zhong
 * @since 2024-03-18
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {

    @Autowired
    OrganizationMapper mapper;

    @Override
    public ResultPage<OrganizationVo> getOrganizationPage(OrganizationQueryDto dto) {

        Page<OrganizationVo> page = ResultPage.toQueryPage(dto.getPageQuery());

        MPJLambdaWrapper<Organization> wrapper = new MPJLambdaWrapper<Organization>()
            .like(StringUtils.isNotBlank(dto.getOrganizationName()), Organization::getOrganizationName,
                dto.getOrganizationName())
            .eq(Organization::getDelState, DelState.UNDELETED)
            // 排序
            .orderByAsc(Organization::getId);
        
        mapper.selectJoinPage(page, OrganizationVo.class, wrapper);

        return ResultPage.fromPage(page);
    }

    @Override
    public Result<Boolean> add(OrganizationAddDto dto) {

        // 校验部门名称是否重复
        Result<Boolean> verifyResult = this.verifyOrgName(dto.getOrganizationName(), null);
        if (!verifyResult.getData()) {
            return verifyResult;
        }

        Organization org = new Organization();
        org.setOrganizationName(dto.getOrganizationName()).setOrganizationDescription(dto.getOrganizationDescription())
            .setCreator(UserInfo.getUserId()).setCreateTm(LocalDateTime.now()).setModifier(UserInfo.getUserId())
            .setModifyTm(LocalDateTime.now()).setDelState(DelState.UNDELETED);

        mapper.insert(org);

        return Result.success("新增部门成功", Boolean.TRUE);
    }

    @Override
    public Result<Boolean> update(OrganizationUpdateDto dto) {
        // 校验部门名称是否重复
        Result<Boolean> verifyResult = this.verifyOrgName(dto.getOrganizationName(), dto.getId());
        if (!verifyResult.getData()) {
            return verifyResult;
        }

        Organization org = mapper.selectById(dto.getId());

        if (org == null || org.getDelState()) {
            return Result.error("没有查到部门信息，请刷新后重试", false);
        }

        org.setOrganizationName(dto.getOrganizationName()).setOrganizationDescription(dto.getOrganizationDescription())
            .setModifier(UserInfo.getUserId()).setModifyTm(LocalDateTime.now());

        mapper.updateById(org);

        return Result.success("修改部门信息成功", true);
    }

    @Override
    public Result<Boolean> delete(Long id) {

        LambdaUpdateWrapper<Organization> updateWrapper = new LambdaUpdateWrapper<Organization>()
            .set(Organization::getDelState, DelState.DELETED).set(Organization::getModifier, UserInfo.getUserId())
            .set(Organization::getModifyTm, LocalDateTime.now()).eq(Organization::getId, id);

        mapper.update(null, updateWrapper);

        return Result.success("删除部门成功", true);
    }

    @Override
    public Result<Boolean> verifyOrgName(String orgName, Long id) {

        if (StringUtils.isBlank(orgName)) {
            return Result.error("部门名称不能为空", false);
        }

        Long count =
            mapper.selectCount(new LambdaQueryWrapper<Organization>().eq(Organization::getOrganizationName, orgName)
                .eq(Organization::getDelState, DelState.UNDELETED).ne(id != null, Organization::getId, id));

        if (count > 0L) {
            return Result.error("部门名称已被使用", false);
        }

        return Result.success("校验通过", true);
    }

    @Override
    public Result<Boolean> setOrgLeader(Long orgId, Long userId) {
        LambdaUpdateWrapper<Organization> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper.set(Organization::getLeaderId, userId);
        updateWrapper.eq(Organization::getId, orgId);

        mapper.update(null, updateWrapper);

        return Result.success("设置部门队长成功", true);
    }

}
